package com.sh.data.engine.domain.dataasset.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sh.data.engine.domain.dataasset.model.domain.TableProductDomain;
import com.sh.data.engine.domain.dataasset.service.TableProductService;
import com.sh.data.engine.domain.datadev.offline.service.DatadevJobService;
import com.sh.data.engine.domain.datadev.offline.service.OfflineDevMenuNodeService;
import com.sh.data.engine.domain.util.ConvertUtil;
import com.sh.data.engine.repository.dao.dataasset.TableProductMapper;
import com.sh.data.engine.repository.dao.dataasset.entity.TableProductEntity;
import com.sh.data.engine.repository.dao.datadev.entity.DatadevJobEntity;
import com.sh.data.engine.repository.dao.datadev.entity.DatadevMenuNodeEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class TableProductServiceImpl extends ServiceImpl<TableProductMapper, TableProductEntity>
    implements TableProductService {
    @Autowired
    private OfflineDevMenuNodeService offlineDevMenuNodeService;

    @Autowired
    private DatadevJobService datadevJobService;

    @Override
    public List<TableProductDomain> getTableProductDomain(Long tblId, Long projectId) {

        LambdaQueryWrapper<TableProductEntity> eq =
            new LambdaQueryWrapper<TableProductEntity>()
                .eq(TableProductEntity::getTblId, tblId)
                .eq(TableProductEntity::getProjectId, projectId)
                .orderByDesc(TableProductEntity::getCreateTime);

        List<TableProductEntity> tableProductResult = this.list(eq);

        List<TableProductDomain> tableProductDomains =
            ConvertUtil.copyProperties(tableProductResult, TableProductDomain.class);

        List<Long> subTaskList =
            tableProductDomains.stream().map(e -> e.getSubTaskId()).collect(Collectors.toList());

        List<Long> taskFlowList =
            tableProductDomains.stream().map(e -> e.getTaskFlowId()).collect(Collectors.toList());

        subTaskList.addAll(taskFlowList);

        List<DatadevMenuNodeEntity> nodeTaskList = offlineDevMenuNodeService.findByIdList(subTaskList);

        Map<Long, String> idMapName =
            nodeTaskList.stream()
                .collect(
                    Collectors.toMap(DatadevMenuNodeEntity::getId, DatadevMenuNodeEntity::getName));

        tableProductDomains.stream()
            .filter(
                e ->
                    (Objects.nonNull(e.getJobId())
                        || (Objects.nonNull(e.getEndTime()) && Objects.nonNull(e.getStatTime()))))
            .forEach(
                e -> {
                    e.setSubTaskName(idMapName.get(e.getSubTaskId()));
                    e.setTaskFlowName(idMapName.get(e.getTaskFlowId()));

                    if (e.getEndTime() != null && e.getStatTime() != null) {
                        e.setExecuteTime(
                            new BigDecimal(e.getEndTime().getTime() - e.getStatTime().getTime())
                                .divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP));

                    } else {
                        DatadevJobEntity jobEntity = datadevJobService.findById(e.getJobId());
                        e.setStatTime(jobEntity.getStartTime());
                        e.setEndTime(jobEntity.getEndTime());
                        e.setExecuteTime(
                            new BigDecimal(
                                jobEntity.getEndTime().getTime() - jobEntity.getStartTime().getTime())
                                .divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP));
                    }
                });
        return tableProductDomains;
    }

    @Override
    public IPage<TableProductDomain> getTableProductDomain(Long tblId, Long projectId,
                                                           Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<TableProductEntity> eq =
            new LambdaQueryWrapper<TableProductEntity>()
                .eq(TableProductEntity::getTblId, tblId)
                .eq(TableProductEntity::getProjectId, projectId)
                .orderByDesc(TableProductEntity::getCreateTime);

        IPage<TableProductDomain> dataApiBaseDomainPageResult =
            page(new Page<>(pageNum, pageSize), eq)
                .convert(e -> Convert.convert(TableProductDomain.class, e));
        List<TableProductDomain> tableProductDomains = dataApiBaseDomainPageResult.getRecords();


        List<Long> subTaskList =
            tableProductDomains.stream().map(e -> e.getSubTaskId()).collect(Collectors.toList());

        List<Long> taskFlowList =
            tableProductDomains.stream().map(e -> e.getTaskFlowId()).collect(Collectors.toList());

        subTaskList.addAll(taskFlowList);

        List<DatadevMenuNodeEntity> nodeTaskList = offlineDevMenuNodeService.findByIdList(subTaskList);

        Map<Long, String> idMapName =
            nodeTaskList.stream()
                .collect(
                    Collectors.toMap(DatadevMenuNodeEntity::getId, DatadevMenuNodeEntity::getName));

        tableProductDomains.stream()
            .filter(
                e ->
                    (Objects.nonNull(e.getJobId())
                        || (Objects.nonNull(e.getEndTime()) && Objects.nonNull(e.getStatTime()))))
            .forEach(
                e -> {
                    e.setSubTaskName(idMapName.get(e.getSubTaskId()));
                    e.setTaskFlowName(idMapName.get(e.getTaskFlowId()));

                    if (e.getEndTime() != null && e.getStatTime() != null) {
                        e.setExecuteTime(
                            new BigDecimal(e.getEndTime().getTime() - e.getStatTime().getTime())
                                .divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP));

                    } else {
                        DatadevJobEntity jobEntity = datadevJobService.findById(e.getJobId());
                        e.setStatTime(jobEntity.getStartTime());
                        e.setEndTime(jobEntity.getEndTime());
                        e.setExecuteTime(
                            new BigDecimal(
                                jobEntity.getEndTime().getTime() - jobEntity.getStartTime().getTime())
                                .divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP));
                    }
                });
        return dataApiBaseDomainPageResult;
    }

    @Override
    public void insetTableProduct(List<TableProductEntity> tableProductEntity) {
        this.saveBatch(tableProductEntity);
    }
}
